/**
 * @depends portlet.js, Window.js
 */
QFinance.portlet.AccountsBalanceHistoryConfigurationWindow = Ext.extend( QFinance.ui.Window, {
    // Default configuration
    configuration: {
        accountID: 0,
        range: 2,
        startDate: null,
        endDate: null,
        type: 1
    },
	
    // Localization
    title: 'Accounts balance history configuration',	
    accountText: 'Account',
    allTimeText: 'All time',
    past30DaysText: 'Past 30 days',
    past60DaysText: 'Past 60 days',
    thisMonthText: 'This month',
    thisYearText: 'This year',
    customText: 'Custom',
    rangeText: 'Range',
    bothText: 'Both',
    incomeText: 'Income',
    expenseText: 'Expense',
    typeText: 'Type',	
    saveText: 'Save',
    closeText: 'Close',
	
    constructor: function(cfg) {
        Ext.apply(this, cfg);
		
        QFinance.portlet.AccountsBalanceHistoryConfigurationWindow.superclass.constructor.call(this);
    },
	
    initComponent: function() {
        this.items = [];
        this.initWindow();        
        this.initStore();
        this.initFormPanel();
        QFinance.portlet.AccountsBalanceHistoryConfigurationWindow.superclass.initComponent.call(this);
    },
	
    initWindow: function() {
        Ext.apply(this, {
            width: 300,
            height: 300,
            autoHeight: true
        });
    },
	
    initStatusBar: function(toolbar) {
        toolbar.add(new Ext.Button({
            text: this.saveText,
            formBind: true,
            scope: this,
            iconCls: 'fugue-disk-black',
            handler: function() {
                if (this.formPanel.getForm().isValid()) {
                    this.doSave();	 
                    this.close();
                }
            }
        }));
				
        toolbar.add(new Ext.Button({
            text: this.closeText,
            iconCls: 'fugue-door-open-out',				
            scope: this,
            handler: function() {
                this.close();
            }
        }));
    },
	
    initStore: function() {
        this.accountStore = new Ext.data.DirectStore({    		
            directFn: QFinance.Remoting.AccountAction.getByAccountTypePlusAll,
            paramsAsHash: false,
            autoLoad: true,
            idProperty: 'id',
            root: 'data',
            successProperty: 'success',
            paramOrder: [ 'type' ],
            baseParams: {
                type: '1'
            },
            fields: [
            {
                name: 'id',
                type: 'int',
                useNull: true
            },
            {
                name: 'accountName'	    		    
            },
            {
                name: 'accountType'
            }
            ],
            listeners: {
                scope: this,
                beforeload: function(store, options) {
                    store.id = this.getProcessStatusManager().start([this]);
                },				
                load: function(store, records, options) {
                    this.getProcessStatusManager().success(store.id);
                    this.accountCombo.setValue(this.configuration.accountID);
                    var range = this.configuration.range;
                    this.rangeCombo.setValue(range);
                    this.updateAccessibleComponents();
                },
                exception: function(dataProxy, type, action, options, response, arg ) {
                    var message = '';
                    var where = '';
                    if (response.result) {
                        message = response.result.message;
                        if (response.result.type == 'exception')
                            where = response.result.where;
                    } else {
                        message = response.message;
                    }
                    this.getProcessStatusManager().error(this.accountStore.id, message);
                    QFinance.service.DeveloperService.log('Store failure: ' + message + ' where\n' + where);
                }
            }		
        });		
    },
    
    updateAccessibleComponents: function() {
        var selectedAccountIndex = this.accountCombo.getValue();
        this.typeCombo.setDisabled( selectedAccountIndex == null );
        
        var selectedRangeIndex = this.rangeCombo.getValue();
        if (selectedRangeIndex >= 0) {
            this.rangeCompositeField.items.each(function(f){
                f.allowBlank = selectedRangeIndex != 6;
                f.clearInvalid();                    
            });                
            this.rangeCompositeField.setDisabled( selectedRangeIndex != 6 );            
        }
    },
	
    initFormPanel: function() {
        this.items.push( this.formPanel = new Ext.form.FormPanel({
            xtype: 'form',
            frame: true,
            labelWidth: 60,
            defaults: {
                anchor: '100%'
            },
            items: [ this.accountCombo = new Ext.form.ComboBox({
                name: 'accountID',
                store: this.accountStore,
                fieldLabel: this.accountText,
                autoSelect: true,
                editable: false,
                triggerAction: 'all',		      		    
                valueField: 'id',
                displayField: 'accountName',
                mode: 'local',
                listeners: {
                    scope: this,
                    select: function(combo, record, index) {
                        this.updateAccessibleComponents();
                    }
                }
            }), this.rangeCombo = new Ext.form.ComboBox({			        	
                name: 'range',
                store: [ 
                [ 1, this.allTimeText ],
                [ 2, this.past30DaysText ],
                [ 3, this.past60DaysText ],
                [ 4, this.thisMonthText ],
                [ 5, this.thisYearText ],
                [ 6, this.customText ]
                ],
                fieldLabel: this.rangeText,
                autoSelect: true,		            	
                editable: false,
                triggerAction: 'all',		      		    		              	
                mode: 'local',
                hiddenName: 'range',              	
                listeners: {
                    scope: this,
                    select: function(combo, record, index) {
                        this.updateAccessibleComponents();
                    }
                }
            }), this.rangeCompositeField = new Ext.form.CompositeField({
                xtype: 'compositefield',
                disabled: true,
                defaults: {
                    flex: 1
                },
                items: [ this.startDateField = new Ext.form.DateField({
                    xtype: 'datefield',
                    name: 'startDate',
                    id: 'startDate',
                    format: "Y-m-d",
                    vtype: 'daterangecomposite',
                    endDateField: 'endDate',
                    allowBlank: true,
                    value: this.configuration.startDate
                }), this.endDateField = new Ext.form.DateField({
                    xtype: 'datefield',
                    name : 'endDate',
                    id: 'endDate',
                    format: "Y-m-d",
                    vtype: 'daterangecomposite',
                    startDateField: 'startDate',
                    allowBlank: true,
                    value: this.configuration.endDate
                })]
            }), this.typeCombo = new Ext.form.ComboBox({			        	
                name: 'type',
                store: [ 
                [ 1, this.bothText ],
                [ 2, this.incomeText ],
                [ 3, this.expenseText ]
                ],
                disabled: true,
                fieldLabel: this.typeText,
                autoSelect: true,		            	
                editable: false,
                triggerAction: 'all',		      		    		              	
                mode: 'local',
                hiddenName: 'type',
                value: this.configuration.type
            })]
        }));
    },
	
    doSave: function() {
        this.configuration.accountID = this.accountCombo.getValue();
        this.configuration.accountName = this.accountCombo.getRawValue();
        this.configuration.range = this.rangeCombo.getValue();
        this.configuration.rangeName = this.rangeCombo.getRawValue();
        this.configuration.startDate = this.startDateField.getValue();
        this.configuration.endDate = this.endDateField.getValue();
        this.configuration.type = this.typeCombo.getValue();
        this.configuration.typeName = this.typeCombo.getRawValue();
        this.fireEvent('save', this.configuration);
    }
});

Ext.reg('QFinance.portlet.AccountsBalanceHistoryConfigurationWindow', QFinance.portlet.AccountsBalanceHistoryConfigurationWindow);